//
// Created by LoveHoneyYou on 2024-11-18.
//

#include "TcpConnection.h"

TcpConnetion::TcpConnetion(int fd, EventLoop *eventloop)
{
    event_loop_ = eventloop;
    readbuf_ = new Buffer(1024);
    writebuf_ = new Buffer(1024);

    request_ = new HttpRequest;
    response_ = new HttpResponse;

    name_ = "Connection-" + std::to_string(fd);
    channel_ = new Channel(fd,FD_Event::ReadEvent,Process_Read,Process_Write,Destroy,this);
    event_loop_->Add_Task(channel_,ElemType::ADD);
}

int TcpConnetion::Process_Read(void *arg)
{
    TcpConnetion* conn = (TcpConnetion*)arg;
    int socket = conn->channel_->Get_Socket();
    int count = conn->readbuf_->Socket_Read(socket);
    if (count > 0)
    {
        // 接收到了 http 请求, 解析http请求
#ifdef MSG_SEND_AUTO
        conn->m_channel->writeEventEnable(true);
        conn->m_evLoop->addTask(conn->m_channel, ElemType::MODIFY);
#endif
        bool flag = conn->request_->parseHttpRequest(
                conn->readbuf_, conn->response_,
                conn->writebuf_, socket);
        if (!flag)
        {
            // 解析失败, 回复一个简单的html
            std::string errMsg = "Http/1.1 400 Bad Request\r\n\r\n";
            conn->writebuf_->Append_Buffer(errMsg);
        }
    }
    else
    {
#ifdef MSG_SEND_AUTO
        // 断开连接
        conn->m_evLoop->(conn->m_channel, ElemType::DELETE);
#endif

    }
#ifndef MSG_SEND_AUTO
    // 断开连接
    conn->event_loop_->Add_Task(conn->channel_, ElemType::DELETE);
#endif
    return 0;
}


int TcpConnetion::Process_Write(void *arg)
{
    TcpConnetion* conn = (TcpConnetion*)arg;
    int count = conn->writebuf_->Send_Data(conn->channel_->Get_Socket());
    if(count > 0)
    {
        if(conn->writebuf_->Read_Able_Size() == 0)
        {
            conn->channel_->Write_Event_Enable(false);
            conn->event_loop_->Add_Task(conn->channel_,ElemType::MODIFY);
            conn->event_loop_->Add_Task(conn->channel_,ElemType::DELETE);
        }
    }
    return 0;
}

int TcpConnetion::Destroy(void *arg)
{
    TcpConnetion* conn = (TcpConnetion*)arg;
    delete conn;
    return 0;
}

TcpConnetion::~TcpConnetion()
{
    if(readbuf_ && readbuf_->Read_Able_Size() == 0 && writebuf_ && writebuf_->Write_Able_Size() == 0)
    {
        delete readbuf_;
        delete writebuf_;
        delete request_;
        delete response_;
        event_loop_->Free_Channel(channel_);
    }
}